<template>
  <div class="personal">
    <el-row>
      <!-- 个人信息 -->
      <el-col :xs="24" :sm="24">
        <el-card shadow="hover" header="个人信息">
          <div class="personal-user">
            <div class="personal-user-left">
              <!--<el-upload class="h100 personal-user-left-upload" action="https://jsonplaceholder.typicode.com/posts/"-->
              <!--           multiple :limit="1">-->
              <!--  <img :src="userInfo.avatar"/>-->
              <!--</el-upload>-->

              <el-upload class="h100 personal-user-left-upload"
                         :action="uploadUrl" multiple :limit="1"
                         ref="uploadRef"
                         :on-success="onSuccess"
                         :on-error="onError"
                         :before-upload="handlerBefore"
                         :file-list="uploadFileList"
                         :show-file-list="false">
                <img v-if="userInfo.avatar" :src="userInfo.avatar"/>
                <el-icon v-if="!userInfo.avatar" class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>

            </div>
            <div class="personal-user-right">
              <el-row>
                <el-col :span="24" class="personal-title mb18">{{
                    currentTime
                  }}，{{ userInfo.userName }}，生活变的再糟糕，也不妨碍我变得更好！
                </el-col>
                <el-col :span="24">
                  <el-row>
                    <el-col :xs="24" :sm="8" class="personal-item mb6">
                      <div class="personal-item-label">昵称：</div>
                      <div class="personal-item-value">{{ userInfo.nickName }}</div>
                    </el-col>
                    <el-col :xs="24" :sm="16" class="personal-item mb6">
                      <div class="personal-item-label">身份：</div>
                      <div class="personal-item-value">{{ userInfo.roleNames }}</div>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="24">
                  <el-row>
                    <el-col :xs="24" :sm="8" class="personal-item mb6">
                      <div class="personal-item-label">登录IP：</div>
                      <div class="personal-item-value">{{ userInfo.lastLoginIp }}</div>
                    </el-col>
                    <el-col :xs="24" :sm="16" class="personal-item mb6">
                      <div class="personal-item-label">登录时间：</div>
                      <div class="personal-item-value">{{ userInfo.lastLoginTime }}</div>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-card>
        <el-card shadow="hover" class="mt15 personal-edit" header="更新信息">
          <div class="personal-edit-safe-box">
            <div class="personal-edit-safe-item">
              <div class="personal-edit-safe-item-left">
                <div class="personal-edit-safe-item-left-label">账户密码</div>
              </div>
              <div class="personal-edit-safe-item-right">
                <el-button text type="primary" @click="runUpdatePwd">立即修改</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
        v-model="showResetPwd"
        title="密码修改"
        width="30%"
        :before-close="cancel"
    >
      <el-form
          label-position="left"
          label-width="100px"
          :model="updatePwdVo"
          ref="formView"
          :rules="rules"
          style="max-width: 460px"
      >
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input type="password" v-model="updatePwdVo.oldPwd"/>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input type="password" v-model="updatePwdVo.newPwd"/>
        </el-form-item>
        <el-form-item label="新密码确认" prop="newPwdOnce">
          <el-input type="password" v-model="updatePwdVo.newPwdOnce"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {resetPwd,resetAvatar} from "/@/api/auth/user";
import {formatAxis} from '/@/utils/formatTime';
import { Plus } from '@element-plus/icons-vue'
import {getUploadFileMaxSize} from "/@/api/oss";
import {Session} from '/@/utils/storage';

const uploadUrl = import.meta.env.VITE_PUBLIC_PATH + '/sysOss/upload'
import {ElMessage} from "element-plus";

const currentTime = computed(() => {
  return formatAxis(new Date());
});
const showResetPwd = ref(false)
const fileSize = ref(0)
const formView = ref()
const uploadRef = ref()
const checkPwd = (rule, value, callback) => {
  if (!value || value === '' || value !== updatePwdVo.newPwdOnce) {
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}

const checkPwdOnce = (rule, value, callback) => {
  if (!value || value === '' || value !== updatePwdVo.newPwd) {
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}
const rules = reactive({
  oldPwd: [{required: true, message: '请输入旧密码', trigger: 'blur'}],
  newPwd: [{validator: checkPwd, trigger: 'blur'}],
  newPwdOnce: [{validator: checkPwdOnce, trigger: 'blur'}],
})

const runUpdatePwd = () => {
  showResetPwd.value = true
}

let userInfo = reactive({
  userName: undefined,
  avatar: undefined,
  nickName: undefined,
  roleNames: undefined,

})
const updatePwdVo = reactive({
  oldPwd: undefined,
  newPwd: undefined,
  newPwdOnce: undefined,
})
//文件上传成功时的钩子
const onSuccess = async (response, uploadFile, uploadFiles) => {
  let {code} = response
  if (code === 200) {
    userInfo.avatar = response.data.fileOssUrl
    uploadFileList.value = []
    uploadRef.value.clearFiles()
    await resetAvatar({avatar:userInfo.avatar}).then(res => {
      if (code === 200) {
        ElMessage.success("头像上传成功")
      }
    })

  }
}
//文件上传失败时的钩子
const onError = (error, uploadFile, uploadFiles) => {
  ElMessage.error("文件上传失败，请重试")
}
const handlerBefore = (file) => {
  if (checkSize(file)) {
    return true
  } else {
    ElMessage.error("上传文件大小不能超过:" + (fileSize.value / 1024 / 1024) + "MB")
    return false
  }
}
const uploadFileList = ref([])
const checkSize = (file) => {
  return file.size < fileSize.value
}
const cancel = () => {
  showResetPwd.value = false
  updatePwdVo.oldPwd = undefined
  updatePwdVo.newPwd = undefined
  updatePwdVo.newPwdOnce = undefined
  formView.value.clearValidate()
  formView.value.resetFields()
}

const submit = async () => {
  await formView.value.validate((valid, fields) => {
    if (valid) {
      resetPwd(updatePwdVo).then(res => {
        ElMessage.success(res.msg)
        cancel()
      })
    }
  })
}


onBeforeMount(() => {
  getUploadFileMaxSize().then(res => {
    fileSize.value = res.data
  })
  let tempUser = Session.get('userInfo')
  userInfo.userName = tempUser.userName
  userInfo.avatar = tempUser.avatar
  userInfo.nickName = tempUser.nickName
  userInfo.lastLoginIp = tempUser.lastLoginIp
  userInfo.lastLoginTime = tempUser.lastLoginTime
  userInfo.roleNames = tempUser.roleNames
})
</script>

<style scoped lang="scss">
@import '../../../theme/mixins/index.scss';

.personal {
  .personal-user {
    height: 130px;
    display: flex;
    align-items: center;

    .personal-user-left {
      width: 100px;
      height: 130px;
      border-radius: 3px;

      ::v-deep(.el-upload) {
        height: 100%;
      }

      .personal-user-left-upload {
        img {
          width: 100%;
          height: 100%;
          border-radius: 3px;
        }

        &:hover {
          img {
            animation: logoAnimation 0.3s ease-in-out;
          }
        }
      }
    }

    .personal-user-right {
      flex: 1;
      padding: 0 15px;

      .personal-title {
        font-size: 18px;
        @include text-ellipsis(1);
      }

      .personal-item {
        display: flex;
        align-items: center;
        font-size: 13px;

        .personal-item-label {
          color: var(--el-text-color-secondary);
          @include text-ellipsis(1);
        }

        .personal-item-value {
          @include text-ellipsis(1);
        }
      }
    }
  }

  .personal-info {
    .personal-info-more {
      float: right;
      color: var(--el-text-color-secondary);
      font-size: 13px;

      &:hover {
        color: var(--el-color-primary);
        cursor: pointer;
      }
    }

    .personal-info-box {
      height: 130px;
      overflow: hidden;

      .personal-info-ul {
        list-style: none;

        .personal-info-li {
          font-size: 13px;
          padding-bottom: 10px;

          .personal-info-li-title {
            display: inline-block;
            @include text-ellipsis(1);
            color: var(--el-text-color-secondary);
            text-decoration: none;
          }

          & a:hover {
            color: var(--el-color-primary);
            cursor: pointer;
          }
        }
      }
    }
  }

  .personal-recommend-row {
    .personal-recommend-col {
      .personal-recommend {
        position: relative;
        height: 100px;
        border-radius: 3px;
        overflow: hidden;
        cursor: pointer;

        &:hover {
          i {
            right: 0px !important;
            bottom: 0px !important;
            transition: all ease 0.3s;
          }
        }

        i {
          position: absolute;
          right: -10px;
          bottom: -10px;
          font-size: 70px;
          transform: rotate(-30deg);
          transition: all ease 0.3s;
        }

        .personal-recommend-auto {
          padding: 15px;
          position: absolute;
          left: 0;
          top: 5%;
          color: var(--next-color-white);

          .personal-recommend-msg {
            font-size: 12px;
            margin-top: 10px;
          }
        }
      }
    }
  }

  .personal-edit {
    .personal-edit-title {
      position: relative;
      padding-left: 10px;
      color: var(--el-text-color-regular);

      &::after {
        content: '';
        width: 2px;
        height: 10px;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        background: var(--el-color-primary);
      }
    }

    .personal-edit-safe-box {
      border-bottom: 1px solid var(--el-border-color-light, #ebeef5);
      padding: 15px 0;

      .personal-edit-safe-item {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .personal-edit-safe-item-left {
          flex: 1;
          overflow: hidden;

          .personal-edit-safe-item-left-label {
            color: var(--el-text-color-regular);
            margin-bottom: 5px;
          }

          .personal-edit-safe-item-left-value {
            color: var(--el-text-color-secondary);
            @include text-ellipsis(1);
            margin-right: 15px;
          }
        }
      }

      &:last-of-type {
        padding-bottom: 0;
        border-bottom: none;
      }
    }
  }
}
</style>
